﻿using System;
using System.Linq;
using System.Diagnostics;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using NPMonitor.DataModel;
using NPMonitor.DataModel.Internal;
using NPMonitor.Implementation;
using NPMonitor.Implementation.Internal;
using NPMonitor.Interfaces;
using NPMonitor.Interfaces.Internal;
using NPMonitor.Helpers;
using System.Threading;

namespace NPMonitor.Launcher.Tests.Service
{
    [TestClass]
    public class JobExecutorTest
    {
        [TestMethod]
        public void KillProcessTest()
        {
            string processName = "iexplore";
            Process[] processArray = Process.GetProcessesByName(processName);

            foreach (Process proc in processArray)
            {
                if (!proc.HasExited && !proc.CloseMainWindow())
                {
                    proc.Kill();
                    proc.WaitForExit(1000);
                    Thread.Sleep(1000);
                }
            }

            Thread.Sleep(1000);

            Assert.IsTrue(Process.GetProcessesByName(processName).Count() == 0);
        }

        [TestMethod]
        public void JobExecutionTest()
        {
            JobData jobData = StoreManager.Current.JobStore.GetJobs(take: int.MaxValue, jobStatuses: new JobStatus[] { JobStatus.Ready }).FirstOrDefault();

            if (jobData != null)
            {
                AppDomain execDomain = JobFileLoader.NewJobExecutionDomain();

                IJob backgroundJob = JobFileLoader.NewJobInstance(execDomain, jobData.TaskId.Value);

                string jobDataStr = Utils.SerializeObject(jobData, typeof(JobData));

                JobExecutionResult returnValue = backgroundJob.Execute(jobDataStr, Guid.NewGuid());
            }
        }

        [TestMethod]
        public void DefaultJobExecutorTest()
        {
            IJobExecutor jobExector = new DefaultJobExecutor();
            IJobManager jobManager = new JobManager();
            JobData jobData = StoreManager.Current.JobStore.GetJobs(take: int.MaxValue, jobStatuses: new JobStatus[] { JobStatus.Ready }).FirstOrDefault();

            if (jobData != null)
            {
                JobContext jobContext = new JobContext(jobManager, jobData, null);

                jobExector.ExecuteJob(jobContext);
            }

            System.Threading.Thread.Sleep(10);
        }
    }
}
